﻿using Core.Language;
using Core.Utility.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Core.ValidateRules.Lib
{
    /// <summary>
    /// 基础验证属性 - 带本地化
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class ValidateRulesBaseAttribute : ValidationAttribute
    {
        /// <summary>
        /// 本地化错误信息字符串
        /// </summary>
        protected string LocalizeErrorMessageString
        {
            get
            {
                if (!string.IsNullOrEmpty(ErrorMessageString))
                {
                    return LanguageResource.GetResourceValue(ErrorMessageString).GetValueOrDefault();
                }
                else
                {
                    return ErrorMessageString;
                }
            }
        }

        /// <summary>
        ///     Default constructor.
        /// </summary>
        /// <remarks>
        ///     This constructor selects a reasonable default error message for
        ///     <see cref="ValidationAttribute.FormatErrorMessage" />
        /// </remarks>
        public ValidateRulesBaseAttribute()
            : base()
        {

        }

        /// <summary>
        /// 重写自 <see cref="ValidationAttribute.IsValid(object)" />
        /// 所有继承自 <see cref="ValidateRulesBaseAttribute"/> 的子类，都应当重写当前方法，否则永远返回错误信息
        /// </summary>
        /// <param name="value">要测试的值</param>
        /// <returns>
        /// 规则校验不通过返回false
        /// </returns>
        public override bool IsValid(object? value)
        {
            return false;
        }

        /// <summary>
        /// 验证返回的最终结果，可通过该方法进行拦截，输出本地化后的对象
        /// </summary>
        /// <param name="value"></param>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            //拦截上下文对象中的DisplayName属性，做本地化转换
            // call overridden method.
            string localizeDisplayName = LanguageResource.GetResourceValue(validationContext.DisplayName).GetValueOrDefault();
            if (!IsValid(value))
            {
                string[]? memberNames = validationContext.MemberName is { } memberName
                    ? new[] { memberName }
                    : null;
                var result = new ValidationResult(string.Format(LocalizeErrorMessageString,localizeDisplayName),memberNames);
                return result;
            }
            return ValidationResult.Success;
        }

    }
}
